﻿using CommunityToolkit.Mvvm.ComponentModel;
using System.Net.Http;
using System.Text;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Threading;

namespace WPFYuanShenDrawingVisual.ViewModels;

public partial class MainViewModel : ObservableObject
{
    [ObservableProperty] private ImageSource _imageSource;
    [ObservableProperty] private string _currentTime;
    [ObservableProperty] private Image[] _images;
    [ObservableProperty] private string _weather;

    private DispatcherTimer timer;
    public MainViewModel()
    {
        Images = GetImageSource();
        ImageSource = Images[61].Source;
        Weather = GetWeather();
        CurrentTime = DateTime.Now.ToString("HH:mm:ss");
        timer = new DispatcherTimer();
        timer.Interval = TimeSpan.FromSeconds(1);
        timer.Tick += (sender, args) =>
        {
            CurrentTime = DateTime.Now.ToString("HH:mm:ss");
        };
        timer.Start();
    }

    public string GetWeather()
    {
        var sb = new StringBuilder();
        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Add("User-Agent", "MobileQQ/5.30.5");
        client.DefaultRequestHeaders.Add("Host", "d1.weather.com.cn");
        client.DefaultRequestHeaders.Add("Referer", "http://hunan.promotion.weather.com.cn/");
        var result = client.GetStringAsync("http://d1.weather.com.cn/sk_2d/101200101.html").Result[11..];
        var jsonNode = JsonObject.Parse(result);
        sb.AppendLine($" {jsonNode!["date"]} {jsonNode!["cityname"]} ");
        sb.AppendLine($"天气：{jsonNode!["weather"]}，当前温度：{jsonNode!["temp"]}℃");
        sb.AppendLine($"湿度：{jsonNode!["SD"]}，空气质量：{jsonNode!["aqi"]}");
        return sb.ToString();
    }

    public Image[] GetImageSource()
    {
        List<Image> images = new();
        string url = "https://content-static.mihoyo.com/content/ysCn/getContentList?pageSize=206&pageNum=1&order=asc&channelId=350";
        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Add("User-Agent", "MobileQQ/5.30.5");
        var result = client.GetStringAsync(url).Result;
        Regex regex = new Regex(@"(?<=""url"":"")(.*?\.png)(?="")");
        var matches = regex.Matches(result);
        foreach (var match in matches)
        {
            if (((Match)match).Value.Contains("{") || ((Match)match).Value.Contains("[")) continue;
            images.Add(new Image() { Source = (ImageSource)new ImageSourceConverter().ConvertFromString(((Match)match).Value.Replace(@"\/", "/"))! });
        }
        return images.ToArray();
    }
}

